<template>
  <div id="edit_medical">
    <header>
      <span @click="goBack()">取消</span>
      <div v-if="status == 'add'">新建病历</div>
      <div v-if="status == 'edit'">编辑病历</div>
      <span @click='save'>保存</span>
    </header>
    <!-- 日期选择 -->
    <!-- <div class='mc' v-show='isTime' @click.stop='toggle(0)'></div>
        <div class='datetime'>
            <div class='top'>
                <a @click.stop='toggle(0)'>取消</a>
                <a @click.stop='sureTime'>确定</a>
            </div>
            <mt-picker :slots="slotsTime" @change="onValuesChangeTime"></mt-picker>
        </div> -->
    <!-- 诊断类型选择 -->
    <div class='mc' v-show='isType' @click.stop='isType=false'>
      <div class='duration' @click.stop='isType=true'>
        <div class='top'>
          <a @click.stop='isType=false'>取消</a>
          <a @click.stop='sureDuration'>确定</a>
        </div>
        <mt-picker :slots="slots" @change="onValuesChange"></mt-picker>
      </div>
    </div>

    <div class="marks" v-if="showMarks">

      <div class="allTime">
        <div @click.stop='showMarks=false' style="width:97%;
            height:0.4rem;
            position: absolute;">
          <i style="background: #000;
                  width:0.15rem;
                  height: 1px;
                  position: absolute;
                  transform: rotate(135deg);
                  top: 0.1rem;
                  right: 0.05rem;"></i>
          <i style="background: #000;
              transform: rotate(45deg);
              width:0.15rem;
              height: 1px;
              position: absolute;
              top: 0.1rem;
              right: 0.05rem;"></i>
        </div>
        <ul class="ltip">
          <el-menu default-active="1" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
            <el-submenu v-for="(item,index) in kindlist" :index="index+''" :key="index">
              <span slot="title" style="letter-spacing:0.01rem;" @click=select1(item.id)>{{item.name}}</span>
              <el-submenu v-for="(item,index) in item.childItems" :index="item.id+''" :key="index">
                <span slot="title" style="letter-spacing: 0.01rem;" @click=select1(item.id)>{{item.name}}</span>
                <el-menu-item index="item.id+''" style="letter-spacing: 0.01rem;" v-for="(item,index) in item.childItems"
                  @click=select1(item.id)>
                  <span slot="title">{{item.name}} </span>
                </el-menu-item>
              </el-submenu>
            </el-submenu>
          </el-menu>
        </ul>
        <div style="background: rgba(64, 158, 255 ,0.5);
              position: fixed;
              bottom: 0px;
              left: 0px;
              width: 100%;
              height: 30px;
              line-height: 30px;
              border-bottom-right-radius: 8px;
              border-bottom-left-radius: 8px;
              text-align: center;"
          @click=sure()>确定</div>
      </div>
    </div>
    <div class='content' style="margin-bottom:50px">
      <ul>
        <li class='noBack' v-if="name=='clinic'">
          <span>配台护士:</span>
          <input type="text" v-model="nurse" placeholder="请输入你自己的真实姓名">
        </li>
        <li @click='select()'>
          <span>类型:</span>
          <i>{{type|| '未选择'}}</i>
        </li>

        <li>
          <span>主诉:</span>
          <input type="text" v-model="obj.complaint" placeholder="请输入主诉">
        </li>
        <li>
          <span>现病史:</span>
          <input type="text" v-model="obj.current" placeholder="请输入现病史">
        </li>
        <li>
          <span>既往史:</span>
          <input type="text" v-model="obj.history" placeholder="请输入既往史">
        </li>
        <li>
          <span>检查:</span>
          <input type="text" v-model="obj.inspection" placeholder="请输入检查结果">
        </li>
        <li>
          <span>辅助检查:</span>
          <input type="text" v-model="obj.assist_check" placeholder="请输入辅助检查结果">
        </li>
        <li style="border-bottom: 0px">
          <span>影像资料:</span>
        </li>
        <li style="padding-bottom: 10px;">
          <a style="display: flex;">
            <el-upload v-for='x in 6' class="avatar-uploader" :action='$api.baseURLUpload+"/photos/upload_shop"'
              :show-file-list="false" :on-success="(res,file)=>{
                        return handleAvatarSuccess(res,file,x-1)
                    }"
              :before-upload="beforeAvatarUpload">
              <img v-if="relPic[x-1]" :src="relPic[x-1]" class="avatar" style="height:0.42rem">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </a>
        </li>
        <li>
          <span>诊断:</span>
          <input type="text" v-model="obj.diagnose" placeholder="请输入诊断">
        </li>
        <li>
          <span>治疗方案:</span>
          <input type="text" v-model="obj.treatment" placeholder="请输入治疗方案">
        </li>
        <li>
          <span>治疗:</span>
          <input type="text" v-model="obj.cure" placeholder="请输入治疗">
        </li>
        <li>
          <span>医嘱:</span>
          <input type="text" v-model="obj.advice" placeholder="请填写医嘱">
        </li>
        <li v-if="name=='doctor'">
          <span>医生签字:</span>
          <input type="text" v-model="obj.sign" placeholder="请输入自己的真实姓名">
        </li>
      </ul>

    </div>

  </div>
</template>
<script>
  export default {
    data() {
      return {
        showMarks: false,
        id: '', //病历id
        type: '', //类型
        status: '', //编辑or新建
        kindlist: [], //病历种类
        kindIndex: '',
        doctorname: '',
        // doctornumber: '',
        doctorid: '',
        relPic: '',
        nurse: '', //护士
        obj: {
          menu: '', //类型
          complaint: '', //主诉
          current: '', //现代
          history: '', //既往
          inspection: '', //检查  
          assist_check: '', //辅助检查
          diagnose: '', // 诊断
          treatment: '', //治疗方案
          cure: '', //治疗
          advice: '', //医嘱
          sign: '', //签字
          relPic: '', //影像资料
          pid: '', //患者id
          clinic_id: '', //诊室的id
          doctor_id: '', //医生的id
          //   // time: '',
          //   id:'',
          //   remarks: '', //备注
          status: '',
        },

        isTime: false, //是否显示时间选择器
        valuestime: '', //就诊时间选择但未确定时的选项
        relPic: [],
        slotsTime: [{
            flex: 1,
            values: function () {
              const date = new Date();
              const year = date.getFullYear();
              const yearArr = [];
              for (var i = year; i < year + 10; i++) {
                yearArr.push(i);
              }
              return yearArr;
            }(),
            className: 'slot1',
            textAlign: 'center'
          },
          {
            flex: 1,
            values: function () {
              const monthArr = [];
              for (var i = 1; i < 13; i++) {
                if (i < 10) {
                  monthArr.push('0' + i);
                } else {
                  monthArr.push(i);
                }

              }
              return monthArr;
            }(),
            className: 'slot2',
            textAlign: 'center'
          },
          {
            flex: 1,
            values: function () {
              const dayArr = [];
              for (var i = 1; i < 32; i++) {
                if (i < 10) {
                  dayArr.push('0' + i);
                } else {
                  dayArr.push(i);
                }

              }
              return dayArr;
            }(),
            className: 'slot3',
            textAlign: 'center'
          },
          {
            flex: 1,
            values: function () {
              const hourArr = [];
              for (var i = 0; i < 24; i++) {
                if (i < 10) {
                  hourArr.push('0' + i);
                } else {
                  hourArr.push(i);
                }

              }
              return hourArr;
            }(),
            className: 'slot4',
            textAlign: 'center'
          },
          {
            flex: 1,
            values: function () {
              const minArr = [];
              for (var i = 0; i < 60; i++) {
                if (i < 10) {
                  minArr.push('0' + i);
                } else {
                  minArr.push(i);
                }
              }
              return minArr;
            }(),
            className: 'slot5',
            textAlign: 'center'
          }
        ],
        isType: false, //是否显示时长选择器
        values: '', //就诊时长选择但未确定时的选项
        slots: [{
          values: [],
          className: 'slot1',
          textAlign: 'center',
          value: [],
        }, ],
      }
    },
    methods: {
      //判断入口返回上一级
      goBack() {
        this.$router.back();
      },
      handleOpen(key, keyPath) {},
      handleClose(key, keyPath) {},
      //初始化
      init() {
        this.name = JSON.parse(localStorage.getItem('type'))
        this.obj.pid = this.$route.query.pid;
        this.doctorid = localStorage.getItem("loginMobile");
      },
      beforeAvatarUpload(file) {
        if (!/image\/\w+/.test(file.type)) {
          this.$utils._toast('请确保文件为图像类型');
          return false;
        }
        if (file.size > 5 * 1024 * 1024) {
          this.$utils._toast('上传图片不能超过5M');
          return false;
        }
      },
      //上传图片
      handleAvatarSuccess(res, file, i) {
        if (res.state == 200) {
          this.$set(this.relPic, i, res.result_origin);
        }
      },
      select() {
        this.showMarks = true;
        var name = '病历模板'
        this.$api.get(this.$api.baseURLSchool, "selecttreedata/view_join_medical_templates/?name=" + name, {}, r => {
          if (r.data.ret == 1) {
            var id = [];
            this.kindlist = r.data.info
          }
        }, err => {
          console.log(err);
        })
      },

      select1(id) {
        this.kindIndex = id;
      },
      sure() {
        this.$api.get(this.$api.baseURLSchool, "selectdata2/view_join_medical_templates?id=" + this.kindIndex, {},
          r => {
            if (r.data.ret == 1) {
              this.showMarks = false;
              this.type = r.data.info[0].name
              if (r.data.info[0].content == '') {
                this.obj.complaint = ''
                this.obj.current = ''
                this.obj.history = ''
                this.obj.inspection = ''
                this.obj.assist_check = ''
                this.obj.diagnose = ''
                this.obj.treatment = ''
                this.obj.cure = ''
                this.obj.advice = ''
              } else {
                this.obj = JSON.parse(r.data.info[0].content)
              }
            }
          }, err => {
            console.log(err);
          })
      },
      //判读入口
      justFrom() {
        if (this.$route.query.status) {
          this.status = this.$route.query.status;
        }
        if (this.$route.query.id) {
          this.id = this.$route.query.id;
          this.$api.get(this.$api.baseURLSchool, "select_cid/medical_records/" + this.id, {}, r => {
            if (r.data.ret == 1) {
              this.obj = r.data.info;
              this.doctorname = r.data.info.doctorname;
              this.relPic = JSON.parse(r.data.info.relPic);
              this.nurse = r.data.info.nurse
              this.type = r.data.info.menu
            }
          }, err => {
            console.log(err);
          })
        }
      },
      // 控制日期选择器显示隐藏动画
      toggle(status) { //status 0隐藏 1显示
        if (status) {
          this.isTime = true;
          $(".datetime").addClass("up").removeClass("down");
        } else {
          $(".datetime").addClass("down").removeClass("up");
          this.isTime = false;
        }
      },
      //就诊时间
      onValuesChangeTime(picker, values) {
        this.valuestime = values[0] + '-' + values[1] + '-' + values[2] + ' ' + values[3] + ':' + values[4];

        function mGetDate(year, month) {
          var d = new Date(year, month, 0);
          return d.getDate();
        }
        var totalDay = mGetDate(values[0], values[1]);
        const dayArr = [];
        for (var i = 1; i < totalDay + 1; i++) {
          if (i < 10) {
            dayArr.push('0' + i);
          } else {
            dayArr.push(i);
          }
        }
        picker.setSlotValues(2, dayArr)
      },
      //确定就诊时间
      sureTime() {
        this.obj.time = this.valuestime;
        this.toggle(0);

      },
      //就诊时长选择
      onValuesChange(picker, values) {
        this.values = values[0];
      },
      //确定就诊时长选择
      sureDuration() {
        this.obj.type = this.values;
        this.isType = false;
        this.select1(this.values)

      },
      //去编辑
      goEdit(param) {
        this.$router.push({
          name: 'editEvery',
          query: {
            key: param
          }
        });
      },
      //上传影像
      goUpload() {
        this.$router.push({
          name: 'docUploadImg'
        });
      },
      //保存病历
      save() {
        if (this.name == 'doctor') {
          this.obj.doctor_id = this.doctorid
        }
        if (this.name == 'clinic') {
          this.obj.clinic_id = this.doctorid
        }
        if (this.status == "add") {
          this.obj.status = 0 //未签字 ，未完成
          this.obj.menu = this.type;
          this.obj.nurse = this.nurse;
          this.obj.pid = this.$route.query.pid;
          this.obj.relPic = JSON.stringify(this.relPic);
          this.$api.post(this.$api.baseURLSchool, "updatedata/medical_records/add", this.obj, r => {
            if (r.data.ret == 1) {
              this.$utils._toast("保存成功");
              setTimeout(() => {
                this.$router.back();
              }, 300);
            }
          }, err => {
            console.log(err);
          })
        } else if (this.status == "edit") {

          if (this.obj.sign != "") {
            if (localStorage.getItem('doctorName') != this.obj.sign) {
              this.obj.status = 0
              this.$utils._toast("签名与认证姓名不符，请填写自己的真实姓名");
              return;
            } else {
              this.obj.status = 1
            }
          } else {
            this.obj.status = 0
          }

          this.obj.menu = this.type;
          this.obj.nurse = this.nurse;
          this.obj.pid = this.$route.query.pid;
          this.obj.relPic = JSON.stringify(this.relPic);
          this.$api.post(this.$api.baseURLSchool, "updatedata/medical_records/edit", this.obj, r => {
            if (r.data.ret == 1) {
              this.$utils._toast("保存成功");
              setTimeout(() => {
                this.$router.back();
              }, 300);
            }
          }, err => {
            console.log(err);
          })
        }
      },

    },
    created() {
      this.justFrom();
      this.init();
    },
    activated() {
      this.justFrom();
    },
  }

</script>
<style lang="scss" scoped>
  #edit_medical .mc {
    z-index: 999;
  }

  #edit_medical .avatar-uploader-icon {
    font-size: 14px;
    color: #BCBBBB;
    width: 44px;
    height: 44px;
    line-height: 44px;
    text-align: center;
    padding-left: 0px;
  }

  .avatar-uploader {
    border: 1px dashed #BCBBBB;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-left: 10px;
    width: 44px;
    height: 44px;
  }


  .el-upload img {
    width: 0.42rem;
    display: block;
  }

</style>
